package com.alibaba.citrus.ots.b2b.trade.order.facade.service;

import com.alibaba.citrus.ots.b2b.trade.order.repository.OrderLineQueryServiceRepository;
import com.alibaba.citrus.ots.common.annotation.FacadeInvoker;
import com.alibaba.citrus.ots.common.annotation.ProcessInvoker;
import com.alibaba.citrus.ots.common.constant.SaleOrderConstants;
import com.alibaba.citrus.ots.common.exception.FacadeException;
import com.alibaba.citrus.ots.common.exception.FunctionException;
import com.alibaba.citrus.ots.common.lock.SaleRedisLock;
import com.alibaba.citrus.ots.common.util.DateUtils;
import com.alibaba.cz.base.tool.StringUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.middleware.cache.runtime.service.EpochCacheService;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.alibaba.nacos.common.utils.MapUtils;
import com.epoch.app.crb2btradecenter.domain.order.service.OrderService;
import com.epoch.app.otsapplicationadaptersdk.service.OtsApplicationAdapterSdkService;
import com.epoch.app.otsb2btradecenter.api.orderlinewrite.service.OrderLineWriteService;
import com.epoch.app.otsb2btradecenter.api.orderquery.service.OrderQueryService;
import com.epoch.app.otsb2btradecenter.api.trademessagelistener.dto.ConsignmentDeleteMessageDealRequest;
import com.epoch.app.otsb2btradecenter.api.trademessagelistener.dto.ConsignmentOrderCreateMessageDealRequest;
import com.epoch.app.otsb2btradecenter.api.trademessagelistener.dto.InvoiceCreateMessageDealRequest;
import com.epoch.app.otsb2btradecenter.api.trademessagelistener.service.TradeMessageListenerService;
import com.epoch.app.otsb2btradecenter.domain.orderline.dto.OrderLineLoadListRequest;
import com.epoch.app.otsb2btradecenter.domain.orderline.model.OrderLine;
import com.epoch.app.otsb2btradecenter.domain.orderline.service.OrderLineService;
import com.epoch.app.otsb2btradecenter.dto.request.OrderPageQueryRequest;
import com.epoch.app.otsb2btradecenter.dto.response.OrderPageQueryResponse;
import com.epoch.app.otsb2btradecenter.model.dto.FeaturesUpdateRequest;
import com.epoch.app.otsb2btradecenter.model.dto.SubFeaturesRequest;
import com.epoch.app.otsunifiedinventory.sdo.ConsignmentOrderLineSDO;
import com.epoch.app.otsunifiedinventory.sdo.ConsignmentOrderSDO;
import com.epoch.app.otsunifiedinventory.sdo.InvoiceOrderDetailSDO;
import com.epoch.app.otsunifiedinventory.sdo.InvoiceOrderSDO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: qianlei
 * @create: 2021/11/10 11:54
 */
@Component
@Primary
public class TradeMessageListenerServiceImpl implements TradeMessageListenerService {

    @Autowired
    private OrderLineWriteService orderLineWriteService;
    @Autowired
    OrderLineQueryServiceRepository orderLineQueryServiceRepository;
    @Autowired
    private OrderQueryService orderQueryService;

    @Autowired
    OrderLineService orderLineService;
    @Autowired
    private OtsApplicationAdapterSdkService otsApplicationAdapterSdkService;

    @Autowired
    private OrderService orderService;
    @Autowired
    private EpochCacheService epochCacheService;
    @Autowired
    private com.epoch.app.crb2btradecenter.domain.orderline.service.OrderLineService  crOrderLineService;
    private final Log log = Log.getLogger(TradeMessageListenerServiceImpl.class);

    @Override
    @FacadeInvoker
    public Result<Void> consignmentOrderCreateMessageDeal(ConsignmentOrderCreateMessageDealRequest consignmentOrderCreateMessageDealRequest) {
        log.info("TradeMessageListenerServiceImpl messageJSON:" + consignmentOrderCreateMessageDealRequest.getOrderJson());
        //解析消息
        ConsignmentOrderSDO consignmentOrderSDO = JSONObject.parseObject(consignmentOrderCreateMessageDealRequest.getOrderJson(),ConsignmentOrderSDO.class);
        try {
            Thread.sleep(8000);
        } catch (InterruptedException e) {
//            e.printStackTrace();
            //todo sap需保证 回调在交货单同步之前，否则需一直保留该处理方式
            log.info("交货单同步时，睡眠等待5s，线程异常");
        }
        //如果不是销售订单交货单，直接返回不处理
        if (StringUtil.isBlank(consignmentOrderSDO.getOuterSalesOrderId())) {
            return Result.success(null);
        }
        // 睡眠方式暂不能控制和015之间的并发，因此目前仍需以外部单号加锁控制
        String lockKey = "sapSync:" + consignmentOrderSDO.getOuterSalesOrderId();
        try(SaleRedisLock lock = new SaleRedisLock("REDIS_CACHE",lockKey, 0, 10 * 60 * 1000)) {
            //加锁
            log.info("consignmentOrderCreateMessageDeal 加锁" + lockKey + "时间:"+ new Date());
            if (!lock.lock()) {
                log.error("consignmentOrderCreateMessageDeal017获取锁失败|外部单号为:" + lockKey);
                throw new FunctionException("OTS-04-001-00-15-038");
            }
            log.info("ThreadId:"+Thread.currentThread().getId()+"|SaleRedis.key="+lockKey+"|lock");
            OrderPageQueryRequest orderPageQueryRequest = new OrderPageQueryRequest();
            orderPageQueryRequest.setOuterOrderId(consignmentOrderSDO.getOuterSalesOrderId());
            Result<List<OrderPageQueryResponse>> result = orderQueryService.pageQuery(orderPageQueryRequest);
            log.info("查询销售订单结果：" + JSON.toJSONString(result));
            if (result == null || CollectionUtils.isEmpty(result.getResult())) {
                log.info("交货单同步时，更新销售订单信息，未查询到销售订单，SAP单号：" + consignmentOrderSDO.getOuterSalesOrderId());
                throw new FacadeException("OTS-05-001-10-16-036");
            }
            OrderPageQueryResponse resp = result.getResult().get(0);

            OrderLineLoadListRequest orderLineLoadListRequest = new OrderLineLoadListRequest();
            orderLineLoadListRequest.setMainOrderId(resp.getId());
            orderLineLoadListRequest.setStart(0);
            orderLineLoadListRequest.setLimit(999);
            Result<List<OrderLine>> listResult = orderLineService.loadOrderLineList(orderLineLoadListRequest);

            if (Objects.isNull(listResult) || CollectionUtils.isEmpty(listResult.getResult())) {
                log.info("consignmentOrderCreateMessageDeal :未查到子单信息");
                return Result.success(null);
            }

            Map<String, ConsignmentOrderLineSDO> consignmentOrderLineSDOMap = new HashMap<>();

            if (CollectionUtils.isNotEmpty(consignmentOrderSDO.getConsignmentOrderLineSDOS())) {
                for (ConsignmentOrderLineSDO consignmentOrderLineSDO : consignmentOrderSDO.getConsignmentOrderLineSDOS()) {
                    if (consignmentOrderSDO.getOuterSalesOrderId() == null || consignmentOrderLineSDO.getOuterSoLineId() == null) {
                        return Result.success(null);
                    }
                    consignmentOrderLineSDOMap.put(consignmentOrderLineSDO.getOuterSoLineId(), consignmentOrderLineSDO);
                }
            }

            //add by 皓晖 at 20211216 for 同步更新信息丢失问题 begin
            //更新销售订单信息
            Map<String, String> mainOrderFeaturesToUpdate = new HashMap<>();
            mainOrderFeaturesToUpdate.put(SaleOrderConstants.DELIVERY_ORDER_ID, consignmentOrderSDO.getOuterDeliveryOrderId());
            FeaturesUpdateRequest featuresUpdateRequest = new FeaturesUpdateRequest();
            featuresUpdateRequest.setMainOrderId(resp.getId());
            featuresUpdateRequest.setOrderSyncVersionToCheck(resp.getSyncVersion());
            featuresUpdateRequest.setMainOrderFeaturesToUpdate(mainOrderFeaturesToUpdate);

            this.orderLineWriteService.updateFeatures(featuresUpdateRequest);


            for (OrderLine orderLine : listResult.getResult()) {
                if (StringUtils.isBlank(orderLine.getOuterOrderLineId())){
                    log.info("consignmentOrderCreateMessageDeal :015未更新外部子单行号");
                    throw new FunctionException("OTS-05-001-10-16-051");
                }
                if (consignmentOrderLineSDOMap.containsKey(orderLine.getOuterOrderLineId())) {
                    Map<String, SubFeaturesRequest> subOrderFeaturesToUpdate = new HashMap<>();
                    //需更新添加的交货单信息
                    Map<String, String> features = new HashMap<>();
                    ConsignmentOrderLineSDO consignmentOrderLineSDO = consignmentOrderLineSDOMap.get(orderLine.getOuterOrderLineId());
                    features.put(SaleOrderConstants.DELIVERY_ORDER_ID, consignmentOrderSDO.getOuterDeliveryOrderId());
                    features.put(SaleOrderConstants.DELIVERY_ORDER_ID_STRING_BUILDER, consignmentOrderSDO.getOuterDeliveryOrderId()+"/");
                    features.put(SaleOrderConstants.DELIVERY_ORDER_LINE_NO, consignmentOrderLineSDO.getOuterOrderLineId());
                    features.put(SaleOrderConstants.DELIVERY_ORDER_CREATOR, consignmentOrderSDO.getCreator());
                    features.put(SaleOrderConstants.DELIVERY_ORDER_CREAT_DATE, DateUtils.toDateStr(consignmentOrderSDO.getCreatDate().getTime(), DateUtils.DATETIME_FORMAT));
                    features.put(SaleOrderConstants.DELIVERY_ORDER_QTY, consignmentOrderLineSDO.getQty());
                    features.put(SaleOrderConstants.DELIVERY_ORDER_POD_STATUS, consignmentOrderLineSDO.getPodStatus());
                    features.put(SaleOrderConstants.DELIVERY_ORDER_POD_QTY, consignmentOrderLineSDO.getPodQty());
//                features.put(SaleOrderConstants.DELIVERY_ORDER_DATE, DateUtils.toDateStr(consignmentOrderSDO.getDeliveryDate().getTime(), DateUtils.DATETIME_FORMAT));
                    features.put(SaleOrderConstants.DELIVERY_BASE_QUANTITY, consignmentOrderLineSDO.getBasicQuantity());
//        features.put(SaleOrderConstants.DELIVERY_ORDER_ZK99,consignmentOrderSDO.getOuterDeliveryOrderId());
//        features.put(SaleOrderConstants.DELIVERY_ORDER_KZWI1,consignmentOrderSDO.getOuterDeliveryOrderId());
                    // fixme 交货单数量单独处理
                    if (StringUtils.isNotBlank(orderLine.getFeatures())) {
                        Map<String, String> orderLineFeatures = JSONObject.parseObject(orderLine.getFeatures(),Map.class);
                        String deliveryQty = orderLineFeatures.get(SaleOrderConstants.DELIVERY_ORDER_QTY);
                        String basicQty = orderLineFeatures.get(SaleOrderConstants.DELIVERY_BASE_QUANTITY);
                        String deliveryId = orderLineFeatures.get(SaleOrderConstants.DELIVERY_ORDER_ID);
                        String doibuilders = orderLineFeatures.get(SaleOrderConstants.DELIVERY_ORDER_ID_STRING_BUILDER);
                        //交货单数量非空，并且交货单不重复，则进行交货单数量累加
                        if (StringUtils.isNotBlank(deliveryQty) && (StringUtils.isBlank(deliveryId) || !deliveryId.equals(consignmentOrderSDO.getOuterDeliveryOrderId()))){
                            log.info("consignmentOrderCreateMessageDeal 销售订单一行多个交货单:" + consignmentOrderSDO.getOuterDeliveryOrderId());
                            BigDecimal qty = new BigDecimal(deliveryQty);
                            if (StringUtils.isNotBlank(consignmentOrderLineSDO.getQty())){
                                qty = qty.add(new BigDecimal(consignmentOrderLineSDO.getQty()));
                            }

                            BigDecimal bQty = new BigDecimal(basicQty);
                            if (StringUtils.isNotBlank(consignmentOrderLineSDO.getBasicQuantity())){
                                bQty = bQty.add(new BigDecimal(consignmentOrderLineSDO.getBasicQuantity()));
                            }
                            features.put(SaleOrderConstants.DELIVERY_BASE_QUANTITY, bQty.setScale(3, RoundingMode.DOWN).toString());
                            features.put(SaleOrderConstants.DELIVERY_ORDER_QTY, qty.setScale(3, RoundingMode.DOWN).toString());
                            features.put(SaleOrderConstants.DELIVERY_ORDER_ID_STRING_BUILDER, doibuilders + consignmentOrderSDO.getOuterDeliveryOrderId() + "/");
                        }
                        if (StringUtils.isNotBlank(basicQty) && (StringUtils.isBlank(deliveryId) || !deliveryId.equals(consignmentOrderSDO.getOuterDeliveryOrderId()))){
                            BigDecimal bQty = new BigDecimal(basicQty);
                            if (StringUtils.isNotBlank(consignmentOrderLineSDO.getBasicQuantity())){
                                bQty = bQty.add(new BigDecimal(consignmentOrderLineSDO.getBasicQuantity()));
                            }
                            features.put(SaleOrderConstants.DELIVERY_BASE_QUANTITY, bQty.setScale(3, RoundingMode.DOWN).toString());
                        }
                    }

                    SubFeaturesRequest subFeaturesRequest = new SubFeaturesRequest();
                    subFeaturesRequest.setSubOrderFeaturesToUpdate(features);
                    //add by 皓晖 at 20211216 for 同步更新增加版本号 begin
                    subFeaturesRequest.setSyncVersion(orderLine.getSyncVersion());
                    //add by 皓晖 at 20211216 for 同步更新增加版本号 end
                    subOrderFeaturesToUpdate.put(String.valueOf(orderLine.getId()), subFeaturesRequest);

                    FeaturesUpdateRequest subFeaturesUpdateRequest = new FeaturesUpdateRequest();
                    subFeaturesUpdateRequest.setMainOrderId(orderLine.getMainOrderId());
                    subFeaturesUpdateRequest.setSubOrderFeaturesToUpdate(subOrderFeaturesToUpdate);

                    orderLineWriteService.updateFeatures(subFeaturesUpdateRequest);

                } else {

                    Map<String, SubFeaturesRequest> subOrderFeaturesToDelete = new HashMap<>();
                    //交货单信息
                    List<String> features = new ArrayList<>();
                    features.add(SaleOrderConstants.DELIVERY_ORDER_ID);
                    features.add(SaleOrderConstants.DELIVERY_ORDER_LINE_NO);
                    features.add(SaleOrderConstants.DELIVERY_ORDER_CREATOR);
                    features.add(SaleOrderConstants.DELIVERY_ORDER_CREAT_DATE);
                    features.add(SaleOrderConstants.DELIVERY_ORDER_QTY);
                    features.add(SaleOrderConstants.DELIVERY_ORDER_POD_STATUS);
                    features.add(SaleOrderConstants.DELIVERY_ORDER_POD_QTY);
                    features.add(SaleOrderConstants.DELIVERY_ORDER_DATE);
                    features.add(SaleOrderConstants.DELIVERY_BASE_QUANTITY);

                    //发票信息
                    features.add(SaleOrderConstants.INVOICE_ID);
                    features.add(SaleOrderConstants.INVOICE_NO);
                    features.add(SaleOrderConstants.INVOICE_TYPE);
                    features.add(SaleOrderConstants.INVOICE_DATE);
                    features.add(SaleOrderConstants.INVOICE_CREATOR);
                    features.add(SaleOrderConstants.INVOICE_CREATE_TIME);
                    features.add(SaleOrderConstants.INVOICE_QTY);
                    features.add(SaleOrderConstants.INVOICE_PRICE);
                    features.add(SaleOrderConstants.INVOICE_ZK01_FEE);

                    SubFeaturesRequest subFeaturesRequest = new SubFeaturesRequest();
                    subFeaturesRequest.setSubOrderFeaturesToDelete(features);

                    subFeaturesRequest.setSyncVersion(orderLine.getSyncVersion());
                    subOrderFeaturesToDelete.put(String.valueOf(orderLine.getId()), subFeaturesRequest);

                    FeaturesUpdateRequest subFeaturesUpdateRequest = new FeaturesUpdateRequest();
                    subFeaturesUpdateRequest.setMainOrderId(orderLine.getMainOrderId());
                    subFeaturesUpdateRequest.setSubOrderFeaturesToDelete(subOrderFeaturesToDelete);

                    orderLineWriteService.updateFeatures(subFeaturesUpdateRequest);

                }
            }




//            //add by 皓晖 at 20211216 for 同步更新信息丢失问题 end
//
//            List<ConsignmentOrderLineSDO> consignmentOrderLineSDOS = consignmentOrderSDO.getConsignmentOrderLineSDOS();
//            for (ConsignmentOrderLineSDO consignmentOrderLineSDO : consignmentOrderLineSDOS) {
//                if (consignmentOrderSDO.getOuterSalesOrderId() == null || consignmentOrderLineSDO.getOuterSoLineId() == null) {
//                    return Result.success(null);
//                }
//
//                OrderLineLoadListRequest orderLinePageQueryRequest = new OrderLineLoadListRequest();
//                orderLinePageQueryRequest.setMainOrderId(resp.getId());
//                orderLinePageQueryRequest.setOuterOrderLineId(consignmentOrderLineSDO.getOuterSoLineId());
//                Result<List<OrderLine>> orderLineList = orderLineService.loadOrderLineList(orderLinePageQueryRequest);
//                if (CollectionUtils.isEmpty(orderLineList.getResult())) {
//                    log.info("交货单同步时，更新销售订单信息，未查询到销售订单，SAP单号：" + consignmentOrderSDO.getOuterSalesOrderId());
//                    throw new FacadeException("未查询到销售订单行");
//                }
//                OrderLine orderLine = orderLineList.getResult().get(0);
//                //交货单信息
//                Map<String, String> features = new HashMap<>();
//                features.put(SaleOrderConstants.DELIVERY_ORDER_ID, consignmentOrderSDO.getOuterDeliveryOrderId());
//                features.put(SaleOrderConstants.DELIVERY_ORDER_LINE_NO, consignmentOrderLineSDO.getOuterOrderLineId());
//                features.put(SaleOrderConstants.DELIVERY_ORDER_CREATOR, consignmentOrderSDO.getCreator());
//                features.put(SaleOrderConstants.DELIVERY_ORDER_CREAT_DATE, DateUtils.toDateStr(consignmentOrderSDO.getCreatDate().getTime(), DateUtils.DATETIME_FORMAT));
//                features.put(SaleOrderConstants.DELIVERY_ORDER_QTY, consignmentOrderLineSDO.getQty());
//                features.put(SaleOrderConstants.DELIVERY_ORDER_POD_STATUS, consignmentOrderLineSDO.getPodStatus());
//                features.put(SaleOrderConstants.DELIVERY_ORDER_POD_QTY, consignmentOrderLineSDO.getPodQty());
////                features.put(SaleOrderConstants.DELIVERY_ORDER_DATE, DateUtils.toDateStr(consignmentOrderSDO.getDeliveryDate().getTime(), DateUtils.DATETIME_FORMAT));
//                features.put(SaleOrderConstants.DELIVERY_BASE_QUANTITY, consignmentOrderLineSDO.getBasicQuantity());
////        features.put(SaleOrderConstants.DELIVERY_ORDER_ZK99,consignmentOrderSDO.getOuterDeliveryOrderId());
////        features.put(SaleOrderConstants.DELIVERY_ORDER_KZWI1,consignmentOrderSDO.getOuterDeliveryOrderId());
//
//                Map<String, SubFeaturesRequest> subOrderFeaturesToUpdate = new HashMap<>();
//                SubFeaturesRequest subFeaturesRequest = new SubFeaturesRequest();
//                subFeaturesRequest.setSubOrderFeaturesToUpdate(features);
//                //add by 皓晖 at 20211216 for 同步更新增加版本号 begin
//                subFeaturesRequest.setSyncVersion(orderLine.getSyncVersion());
//                //add by 皓晖 at 20211216 for 同步更新增加版本号 end
//                subOrderFeaturesToUpdate.put(String.valueOf(orderLine.getId()), subFeaturesRequest);
//
//                FeaturesUpdateRequest subFeaturesUpdateRequest = new FeaturesUpdateRequest();
//                subFeaturesUpdateRequest.setMainOrderId(orderLine.getMainOrderId());
//                subFeaturesUpdateRequest.setSubOrderFeaturesToUpdate(subOrderFeaturesToUpdate);
//
//                orderLineWriteService.updateFeatures(subFeaturesUpdateRequest);
//
//            }
        } catch (Exception e) {
            log.error("更新订单features交货单信息失败:", e);
            throw new FacadeException("OTS-05-001-10-16-035");
        }

        return Result.success(null);
    }

    @Override
    @ProcessInvoker(printLog = true)
    public Result<Void> invoiceCreateMessageDeal(InvoiceCreateMessageDealRequest invoiceCreateMessageDealRequest) {
        log.info("invoiceCreateMessageDeal messageJSON:" + invoiceCreateMessageDealRequest.getMessage());

        InvoiceOrderSDO invoiceOrderSDO = JSONObject.parseObject(invoiceCreateMessageDealRequest.getMessage(), InvoiceOrderSDO.class);
        //如果不是销售订单发票，直接返回不处理
//        if (StringUtil.isBlank(invoiceOrderSDO.getSourceOrderId())) {
//            return Result.success(null);
//        }
        List<InvoiceOrderDetailSDO> items = invoiceOrderSDO.getDetailList();
//        Map<String,List<InvoiceOrderDetailSDO>> saleOrderInvoiceDetails = new HashMap<>();

        Map<String,List<InvoiceOrderDetailSDO>> saleOrderInvoiceDetails = items.stream().filter(invoiceOrderDetailSDO -> StringUtils.isNotBlank(invoiceOrderDetailSDO.getSourceOrderId())).collect(Collectors.groupingBy(InvoiceOrderDetailSDO::getSourceOrderId));
        if (MapUtils.isEmpty(saleOrderInvoiceDetails)){
            log.info("invoiceCreateMessageDeal 源单号为空，直接返回成功");
            return Result.success(null);
        }
        Set<String> sourceIds = saleOrderInvoiceDetails.keySet();
        for (String sourceId : sourceIds) {
            OrderPageQueryRequest orderPageQueryRequest = new OrderPageQueryRequest();
            orderPageQueryRequest.setOuterOrderId(sourceId);
            Result<List<OrderPageQueryResponse>> result = orderQueryService.pageQuery(orderPageQueryRequest);
            if (result == null || org.apache.commons.collections4.CollectionUtils.isEmpty(result.getResult())) {
                throw new FacadeException("OTS-05-001-10-16-036");
            }
            OrderPageQueryResponse resp = result.getResult().get(0);
            List<InvoiceOrderDetailSDO> invoiceOrderDetailSDOList = saleOrderInvoiceDetails.get(sourceId);
            for (InvoiceOrderDetailSDO invoiceOrderDetailSDO : invoiceOrderDetailSDOList) {
                if (invoiceOrderDetailSDO.getSalesOrderLineId() == null) {
                    log.info("invoiceCreateMessageDeal 发票信息中不包含销售订单号信息 "+ invoiceOrderDetailSDO.getInvoiceOrderId());
                    continue;
                }
                OrderLineLoadListRequest orderLinePageQueryRequest = new OrderLineLoadListRequest();
                orderLinePageQueryRequest.setMainOrderId(resp.getId());
                orderLinePageQueryRequest.setOuterOrderLineId(invoiceOrderDetailSDO.getSalesOrderLineId());
                orderLinePageQueryRequest.setStart(0);
                orderLinePageQueryRequest.setLimit(999);
                Result<List<OrderLine>> orderLineList = orderLineService.loadOrderLineList(orderLinePageQueryRequest);
                if (org.apache.commons.collections4.CollectionUtils.isEmpty(orderLineList.getResult())) {
                    throw new FacadeException("OTS-05-001-10-16-027");
                }
                orderLineList.getResult().stream().forEach(orderLine -> {
                    Map<String, String> orderLineFeatures = JSONObject.parseObject(orderLine.getFeatures(),Map.class);
                    if (MapUtils.isNotEmpty(orderLineFeatures)) {
                        String deliveryDelete = orderLineFeatures.get(SaleOrderConstants.DELIVERY_DELETE);
                        if (StringUtils.isNotBlank(deliveryDelete)&&Boolean.TRUE.toString().equalsIgnoreCase(deliveryDelete)){
                            return;
                        }
                    }
                    Map<String, String> features = new HashMap<>();
                    //发票信息
                    features.put(SaleOrderConstants.INVOICE_ID, invoiceOrderSDO.getInvoiceOrderId());
                    //去前导0赋值发票行号
                    features.put(SaleOrderConstants.INVOICE_NO, String.valueOf(Integer.parseInt(invoiceOrderDetailSDO.getOrderLineId())));
                    features.put(SaleOrderConstants.INVOICE_TYPE, invoiceOrderSDO.getType());
                    features.put(SaleOrderConstants.INVOICE_DATE, DateUtils.toDateStr(invoiceOrderSDO.getSapGenerateTime().getTime(), DateUtils.DATETIME_FORMAT));
                    features.put(SaleOrderConstants.INVOICE_CREATOR, invoiceOrderSDO.getCreator());
                    features.put(SaleOrderConstants.INVOICE_CREATE_TIME, DateUtils.toDateStr(invoiceOrderSDO.getCreateDate().getTime(), DateUtils.DATETIME_FORMAT));
                    features.put(SaleOrderConstants.INVOICE_QTY, String.valueOf(invoiceOrderDetailSDO.getQuantity()));
                    //价格是分，不需要转换，由前端处理展示
//                features.put(SaleOrderConstants.INVOICE_FEE, String.valueOf(invoiceOrderDetailSDO.getSubTotalAmount() / 100));
                    features.put(SaleOrderConstants.INVOICE_PRICE, String.valueOf(invoiceOrderDetailSDO.getPrice()));
                    features.put(SaleOrderConstants.INVOICE_ZK01_FEE, String.valueOf(invoiceOrderDetailSDO.getSubTotalAmount()));

                    Map<String, SubFeaturesRequest> subOrderFeaturesToUpdate = new HashMap<>();
                    SubFeaturesRequest subFeaturesRequest = new SubFeaturesRequest();
                    subFeaturesRequest.setSubOrderFeaturesToUpdate(features);
                    subOrderFeaturesToUpdate.put(String.valueOf(orderLine.getId()), subFeaturesRequest);

                    FeaturesUpdateRequest featuresUpdateRequest = new FeaturesUpdateRequest();
                    featuresUpdateRequest.setMainOrderId(orderLine.getMainOrderId());
                    featuresUpdateRequest.setSubOrderFeaturesToUpdate(subOrderFeaturesToUpdate);
                    orderLineWriteService.updateFeatures(featuresUpdateRequest);
                });
            }
        }


        return Result.success(null);
    }

    @Override
    @ProcessInvoker(printLog = true)
    public Result<Void> consignmentDeleteMessageDeal(ConsignmentDeleteMessageDealRequest consignmentDeleteMessageDealRequest) {
        log.info("consignmentDeleteMessageDeal messageJSON:" + consignmentDeleteMessageDealRequest.getMessage());
        //解析消息
        ConsignmentOrderSDO consignmentOrderSDO = JSONObject.parseObject(consignmentDeleteMessageDealRequest.getMessage(), ConsignmentOrderSDO.class);
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            //todo sap需保证 回调在交货单同步之前，否则需一直保留该处理方式
            log.error("交货单删除时，睡眠等待3s，线程异常", e);
        }
        //如果不是销售订单交货单，直接返回不处理
        if (StringUtil.isBlank(consignmentOrderSDO.getOuterSalesOrderId())) {
            return Result.success(null);
        }
        OrderPageQueryRequest orderPageQueryRequest = new OrderPageQueryRequest();
        orderPageQueryRequest.setOuterOrderId(consignmentOrderSDO.getOuterSalesOrderId());
        Result<List<OrderPageQueryResponse>> result = orderQueryService.pageQuery(orderPageQueryRequest);
        log.info("查询销售订单结果：" + JSON.toJSONString(result));
        if (result == null || CollectionUtils.isEmpty(result.getResult())) {
            log.info("交货单删除时，更新销售订单信息，未查询到销售订单，SAP单号：" + consignmentOrderSDO.getOuterSalesOrderId());
            throw new FacadeException("未查询到销售订单");
        }

        OrderPageQueryResponse resp = result.getResult().get(0);
        List<ConsignmentOrderLineSDO> consignmentOrderLineSDOS = consignmentOrderSDO.getConsignmentOrderLineSDOS();
        for (ConsignmentOrderLineSDO consignmentOrderLineSDO : consignmentOrderLineSDOS) {
            if (consignmentOrderSDO.getOuterSalesOrderId() == null || consignmentOrderLineSDO.getOuterSoLineId() == null) {
                return Result.success(null);
            }

            OrderLineLoadListRequest orderLinePageQueryRequest = new OrderLineLoadListRequest();
            orderLinePageQueryRequest.setMainOrderId(resp.getId());
            orderLinePageQueryRequest.setOuterOrderLineId(consignmentOrderLineSDO.getOuterSoLineId());
            orderLinePageQueryRequest.setStart(0);
            orderLinePageQueryRequest.setLimit(999);
            Result<List<OrderLine>> orderLineList = orderLineService.loadOrderLineList(orderLinePageQueryRequest);
            if (CollectionUtils.isEmpty(orderLineList.getResult())) {
                log.info("交货单删除时，更新销售订单信息，未查询到销售订单，SAP单号：" + consignmentOrderSDO.getOuterSalesOrderId());
                throw new FacadeException("未查询到销售订单行");
            }
            OrderLine orderLine = orderLineList.getResult().get(0);


            //删除交货单信息前判断订单上是否有交货单信息
            Map<String,String> featuresMap = JSONObject.parseObject(orderLine.getFeatures(), Map.class);
            if (StringUtils.isNotBlank(orderLine.getRefuseReasonCode()) && StringUtils.isBlank(featuresMap.get("deliveryOrderId"))) {
                continue;
            }
            if (StringUtils.isBlank(featuresMap.get("deliveryOrderId"))) {
                log.info("订单行还未同步交货单号信息，SAP单号：" + consignmentOrderSDO.getOuterSalesOrderId());
                throw new FacadeException("订单行上未查找到对应的交货单信息");
            }

            //交货单信息
            List<String> features = new ArrayList<>();
            features.add(SaleOrderConstants.DELIVERY_ORDER_ID);
            features.add(SaleOrderConstants.DELIVERY_ORDER_LINE_NO);
            features.add(SaleOrderConstants.DELIVERY_ORDER_CREATOR);
            features.add(SaleOrderConstants.DELIVERY_ORDER_CREAT_DATE);
            features.add(SaleOrderConstants.DELIVERY_ORDER_QTY);
            features.add(SaleOrderConstants.DELIVERY_ORDER_POD_STATUS);
            features.add(SaleOrderConstants.DELIVERY_ORDER_POD_QTY);
            features.add(SaleOrderConstants.DELIVERY_ORDER_DATE);
            features.add(SaleOrderConstants.DELIVERY_BASE_QUANTITY);

            //发票信息
            features.add(SaleOrderConstants.INVOICE_ID);
            features.add(SaleOrderConstants.INVOICE_NO);
            features.add(SaleOrderConstants.INVOICE_TYPE);
            features.add(SaleOrderConstants.INVOICE_DATE);
            features.add(SaleOrderConstants.INVOICE_CREATOR);
            features.add(SaleOrderConstants.INVOICE_CREATE_TIME);
            features.add(SaleOrderConstants.INVOICE_QTY);
            features.add(SaleOrderConstants.INVOICE_PRICE);
            features.add(SaleOrderConstants.INVOICE_ZK01_FEE);

            Map<String, SubFeaturesRequest> subOrderFeaturesToDelete = new HashMap<>();
            SubFeaturesRequest subFeaturesRequest = new SubFeaturesRequest();
            subFeaturesRequest.setSubOrderFeaturesToDelete(features);
            //是否是删除交货单，再更新子单features时，打标deliveryDelete=true,便于015接收到发票更新以后，remove掉发票相关的数据
            HashMap<String, String> bizFeatures = new HashMap<>();
            bizFeatures.put(SaleOrderConstants.DELIVERY_DELETE,Boolean.TRUE.toString());
            subFeaturesRequest.setBizFeatures(bizFeatures);
            subOrderFeaturesToDelete.put(String.valueOf(orderLine.getId()), subFeaturesRequest);


            Map<String, String> mainOrderFeaturesToUpdate = new HashMap<>();
            mainOrderFeaturesToUpdate.put(SaleOrderConstants.DELIVERY_ORDER_ID, "");
            mainOrderFeaturesToUpdate.put(SaleOrderConstants.EXT_MESSAGE, "");
            FeaturesUpdateRequest featuresUpdateRequest = new FeaturesUpdateRequest();
            featuresUpdateRequest.setMainOrderId(orderLine.getMainOrderId());
            featuresUpdateRequest.setMainOrderFeaturesToDelete(mainOrderFeaturesToUpdate);
            featuresUpdateRequest.setSubOrderFeaturesToDelete(subOrderFeaturesToDelete);
            orderLineWriteService.updateFeatures(featuresUpdateRequest);
        }

        return Result.success(null);
    }



}
